package com.mz.demo.service.impl;

import com.mz.demo.dao.RegisterMapper;
import com.mz.demo.entity.SysUser;
import com.mz.demo.entity.vo.AccountPasswordInfoVo;
import com.mz.demo.service.RegisterService;
import com.mz.demo.utils.entity.GlobalException;
import com.mz.demo.utils.tools.NicknameGenerate;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private RegisterMapper registerMapper;

    @Override
    @Transactional
    public void registerByAccountPassword(AccountPasswordInfoVo accountPasswordInfoVo) {

        SysUser sysUser = new SysUser();
        sysUser.setUsername(accountPasswordInfoVo.getUsername())
                .setPassword( bCryptPasswordEncoder.encode(accountPasswordInfoVo.getPassword()) )
                .setNickname(NicknameGenerate.generateNickname());

        registerMapper.insert(sysUser);
        return;
    }

    @Override
    @Transactional
    public void logout(Long userId) {

       SysUser sysUser = registerMapper.selectById(userId);
       if( sysUser == null ){
           throw GlobalException.gen(10001, "用户不存在" );
       }
       registerMapper.deleteById(userId);
    }
}
